package com.zhu.user.service.impl;

import com.zhu.user.dao.UserMapper;
import com.zhu.user.model.User;
import com.zhu.user.model.UserCriteria;
import com.zhu.user.service.UserService;
import com.zhu.user.util.PasswordHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by DELL on 2016/1/5.
 */
@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordHelper passwordHelper;

    @Override
    public boolean createUser(User user) {
        user.setSalt(passwordHelper.generateSalt());
        user.setPassword(passwordHelper.encryptPassword(user.getPassword(), user.getSaltSource()));
        user.setRegisterdate(new Date());

        return userMapper.insert(user) == 1;
    }

    @Override
    public boolean changePwd(User user) {
        user.setPassword(passwordHelper.encryptPassword(user.getPassword(), user.getSaltSource()));

        return userMapper.updateByPrimaryKey(user) == 1;
    }

    @Override
    public User getUser(String username) {
        UserCriteria userCriteria = new UserCriteria();
        userCriteria.createCriteria().andUsernameEqualTo(username);

        List<User> userList = userMapper.selectByExample(userCriteria);
        if(userList != null && !userList.isEmpty()){
            return userList.get(0);
        }

        return null;
    }
}
